<template>
  <div>
    <div class="flex-start m-b-30">
      <el-button icon="el-icon-back" plain round size="small" type="primary" @click="back">返回</el-button>
    </div>
    <div class="flex-center">
      <div>{{editObj.deviceName}}
        <el-button v-clipboard="'some text'" type="text">复制</el-button>
      </div>
      <div>
        属性更新时间：{{refreshDate}}
        <el-button class="m-l-5" icon="el-icon-refresh-right" size="small" type="primary" @click="getDetail">刷新</el-button>
      </div>
    </div>
    <div class="flex-center">
      <div>所属产品：{{editObj.productName}}</div>
      <div>
        <span>密码：{{editObj.deviceSecret}}</span>
        <el-button v-clipboard="editObj.deviceSecret" type="text">复制</el-button>
      </div>
      <div>
        <span>productKey：{{editObj.productKey}}</span>
        <el-button v-clipboard="editObj.productKey" type="text">复制</el-button>
      </div>
      <div>
        <span>groupKey：{{editObj.groupKey}}</span>
        <el-button v-clipboard="editObj.groupKey" type="text">复制</el-button>
      </div>
    </div>

    <div class="attrs m-t-10" v-loading="isLoading">
      <attr-card class="card" v-for="({label, value, attrKey, canEdit, unit}, index) in attrs" :key="index" :attr-key="attrKey"
                 :can-edit="canEdit"
                 :unit="unit"
                 :label="label" :value="value" @edit="handleEdit"></attr-card>
    </div>
    <el-dialog width="500px" append-to-body  :title="params.label" :visible.sync="isShowEdit">
      <el-form label-width="100px" label-position="right">
        <tempalte v-if="params.attrKey==='units'">
          <el-form-item label-width="100px"  label="计量单位">
            <el-radio v-model="editObj.units" :label="1">kg</el-radio>
            <el-radio v-model="editObj.units" :label="2">L</el-radio>
          </el-form-item>
        </tempalte>
        <tempalte v-if="params.attrKey==='density'">
          <el-form-item label="密度">
            <el-input v-model="editObj.density"><span slot="suffix">kg/L</span></el-input>
          </el-form-item>
        </tempalte>
        <tempalte v-if="params.attrKey==='sensorConcentrateThreshold' || params.attrKey==='sensorTemperatureThreshold' || params.attrKey==='sensorHeightThreshold'">
          <el-tabs v-model="activeName">
            <el-tab-pane v-for="index in  sensorNum" :label="`传感器${index}`" :name="`sensor${index}`">
              <div class="flex-center" v-if="editObj[params.attrKey][`sensor${index}`]">
                <el-form-item label-width="60px" label="min">
                  <el-input v-model="editObj[params.attrKey][`sensor${index}`].min"><span slot="suffix">{{params.unit}}</span></el-input>
                </el-form-item>
                <el-form-item label-width="60px" label="max">
                  <el-input v-model="editObj[params.attrKey][`sensor${index}`].max"><span slot="suffix">{{params.unit}}</span></el-input>
                </el-form-item>
              </div>
              <div style="text-align: center" v-if="!editObj[params.attrKey][`sensor${index}`]">
                <el-button style="margin: auto" type="primary" icon="el-icon-plus" circle @click="addSensor()"></el-button>
              </div>
            </el-tab-pane>
          </el-tabs>


        </tempalte>

        <template v-if="params.attrKey==='sensorBd'">
          <el-tabs v-model="activeName">
            <el-tab-pane v-for="index in  sensorNum" :label="`传感器${index}`" :name="`sensor${index}`">
              <div class="flex-center" v-for="(item, index) in editObj.sensorBd[activeName]">
                <el-form-item label-width="60px" label="高度">
                  <el-input v-model="item.h"><span slot="suffix">cm</span></el-input>
                </el-form-item>
                <el-form-item label-width="60px" label="容量">
                  <el-input v-model="item.w"><span slot="suffix">kg/L</span></el-input>
                </el-form-item >
                <el-button style="margin-bottom: 22px;margin-left: 10px;" type="danger" icon="el-icon-delete" circle @click="removeBd(editObj.sensorBd[activeName], index)"></el-button>
              </div>
              <div style="text-align: center" >
                <el-button style="margin: auto" type="primary" icon="el-icon-plus" circle @click="addBd(editObj.sensorBd)"></el-button>
              </div>
            </el-tab-pane>
          </el-tabs>
        </template>
        <template v-if="params.attrKey==='precision1' || params.attrKey==='precision2'">
          <el-form-item label-width="100px" label="流量计精度">
            <el-input v-model="editObj[params.attrKey]"></el-input>
          </el-form-item>
        </template>
        <template v-if="params.attrKey==='sensorBh'">
          <el-tabs  v-model="activeName">
            <el-tab-pane v-for="index in  sensorNum" :label="`传感器${index}`" :name="`sensor${index}`">
              <el-form-item label="最大高度">
                <el-input v-model="editObj.sensorBh[`sensor${index}`]"><span slot="suffix">mm</span></el-input>
              </el-form-item>
            </el-tab-pane>
          </el-tabs>

        </template>
      </el-form>
      <div slot="footer"  class="flex-end">
        <el-button size="small" @click="isShowEdit=false">取消</el-button>
        <el-button size="small" type="primary" @click="doConfirm">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>

import AttrCard from "@/views/mainboard/component/AttrCard";
import {
  iotdeviceDetail,
  iotdeviceParamsSet,
  iotdeviceSensorHeightSet, iotdeviceSensorThresholdSet,
  iotdeviceStandardSet
} from "@/api/product/mainboard";
import {getIotProductList} from "@/api/product/product";
import {deepClone} from "@/util/util";

export default {
  name: "BoardDetail",
  components: {AttrCard},
  props: {
    id: String,
  },
  data() {
    return {
      attrs: [
        {label: '流量卡号', value: '', attrKey: 'iccId', canEdit: false},
        {label: '信号值', value: '', attrKey: 'csq', canEdit: false},
        {label: 'MCU', value: '', attrKey: 'mcudat', canEdit: false},
        {label: '电源电压', value: '', attrKey: 'power', canEdit: false},
        {label: '传感器结构数据', value: '', attrKey: 'sensorData', canEdit: false},
        {label: 'GPS', value: '', attrKey: 'gpsMsg', canEdit: false},
        {label: '标定', value: '', attrKey: 'sensorBd', canEdit: true},
        {label: '浓度阈值', value: '', attrKey: 'sensorConcentrateThreshold', canEdit: true, unit: '%'},
        {label: '计量单位', value: '', attrKey: 'units', canEdit: true},
        {label: '密度', value: '', attrKey: 'density', canEdit: true},
        {label: '温度阈值', value: '', attrKey: 'sensorTemperatureThreshold', canEdit: true, unit: '℃'},
        {label: '液位阈值', value: '', attrKey: 'sensorHeightThreshold', canEdit: true, unit: 'mm'},
        {label: '桶最大高度', value: '', attrKey: 'sensorBh', canEdit: true},
        {label: '泵A流量计精度', value: '', attrKey: 'precision1', canEdit: true},
        {label: '泵B流量计精度', value: '', attrKey: 'precision2', canEdit: true},
      ],
      editObj: {},
      isShowEdit: false,
      activeName: 'sensor1',
      refreshDate: '',
      isLoading: false,
      options: [],
      params: '',
      sensorNum: 1
    }
  },
  watch: {
    id: {
      immediate: true,
      handler() {
        if(this.id) {
          this.getDetail()
        }
      }
    }
  },
  methods: {
    doConfirm() {
      let promise = ''

      if(this.params.attrKey==='sensorBh') {
        this.editObj.sensorXh = this.activeName.match(/\d+/g)[0]
        this.editObj.height = this.editObj.sensorBh[this.activeName]
        promise = iotdeviceSensorHeightSet
      } else if (this.params.attrKey==='sensorBd') {
        let reqArr = Object.keys(this.editObj.sensorBd).map(key => {
          if(this.editObj.sensorBd[key]) {
            let xh = key.match(/\d+/g)[0]
            return iotdeviceStandardSet({id: this.editObj.id, sensorXh: xh, standardList: this.editObj.sensorBd[key]})
          }
        })
        promise = () => Promise.all(reqArr)
      } else if(this.params.attrKey==='sensorConcentrateThreshold' || this.params.attrKey==='sensorTemperatureThreshold' || this.params.attrKey==='sensorHeightThreshold') {
        let reqArr = Object.keys(this.editObj[this.params.attrKey]).map(key => {
          if(this.editObj[this.params.attrKey][key]) {
            let sensor = this.editObj[this.params.attrKey][key]
            let xh = key.match(/\d+/g)[0]
            let paramsMap = {
              'sensorConcentrateThreshold': 'concentrate',
              'sensorTemperatureThreshold': 'temperature',
              'sensorHeightThreshold': 'height',
            }
            return iotdeviceSensorThresholdSet({id: this.editObj.id, sensorXh: xh, [`${paramsMap[this.params.attrKey]}Min`]: sensor.min, [`${paramsMap[this.params.attrKey]}Max`]: sensor.max})
          }
        })
        promise = () => Promise.all(reqArr)
      } else {
        promise = iotdeviceParamsSet
      }
      this.editObj.sensorBh = JSON.stringify(this.editObj.sensorBh)
      this.editObj.sensorBd = JSON.stringify(this.editObj.sensorBd)
      this.editObj.sensorConcentrateThreshold = JSON.stringify(this.editObj.sensorConcentrateThreshold)
      this.editObj.sensorTemperatureThreshold = JSON.stringify(this.editObj.sensorTemperatureThreshold)
      this.editObj.sensorHeightThreshold = JSON.stringify(this.editObj.sensorHeightThreshold)
      promise({...this.editObj}).then(res => {
        this.$message.success('设置成功！')
        this.getDetail()
        this.isShowEdit = false
      })
    },
    addSensor() {
      this.$set(this.editObj[this.params.attrKey], this.activeName, {max:'', min: ''})
    },
    removeBd(arr, index) {
      arr.splice(index, 1)
    },
    addBd(sensorbd) {
      if(!sensorbd[this.activeName]) {
        this.$set(sensorbd, this.activeName, [])
      }
      sensorbd[this.activeName].push({w:'',h:''})
    },
    back() {
      this.$emit('back')
    },
    getDetail() {
      this.productList()
      this.isLoading = true
      iotdeviceDetail({id: this.id}).then(res => {
        this.editObj = res.data.data
        this.info = deepClone(res.data.data)
        this.editObj.sensorBh = JSON.parse(this.editObj.sensorBh || '{}')
        this.editObj.sensorBd = JSON.parse(this.editObj.sensorBd || '{}')
        this.editObj.sensorConcentrateThreshold = JSON.parse(this.editObj.sensorConcentrateThreshold || '{}')
        this.editObj.sensorTemperatureThreshold = JSON.parse(this.editObj.sensorTemperatureThreshold || '{}')
        this.editObj.sensorHeightThreshold = JSON.parse(this.editObj.sensorHeightThreshold || '{}')
        this.attrs.forEach(attr => {
          attr.value = this.info[attr.attrKey]
          if(attr.attrKey == 'units') {
            attr.value = attr.value===1 ? 'kg':'L'
          }
        })
        this.sensorNum = Object.keys(JSON.parse(this.editObj.sensorData || '{}')).length
        this.refreshDate = new Date().toLocaleString()
      }).finally(() => {
        this.isLoading = false
      })
    },
    productList(){
      getIotProductList().then(res => {
        this.options = res.data.data
      })
    },
    handleEdit(attr) {
      this.params = attr
      this.isShowEdit = true
      console.log('attr', attr)
    }
  }
}
</script>

<style scoped lang="scss">
.attrs {
  display: flex;
  flex-wrap: wrap;

  .card {
    margin-right: 30px;
    margin-bottom: 30px;
  }
}
</style>
